package top.went.db.dao;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import top.went.pojo.RoleEntity;

import java.util.List;

public interface RoleDao extends CrudRepository<RoleEntity, Long> {

    /**
     * 查找所有角色
     *
     * @return
     */
//    @Query("from RoleEntity r where r.roleIsDel = 0 order by r.roleId desc")
//    public List<RoleEntity> queryAll(Pageable pageable);
    public List<RoleEntity> findAllByRoleIsDelOrderByRoleIdDesc(Long del, Pageable pageable);

    /**
     * 有效角色计数
     *
     * @param del
     * @return
     */
    public long countAllByRoleIsDel(Long del);

    /**
     * 角色模糊查询计数
     *
     * @param name
     * @param del
     * @return
     */
    public long countAllByRoleNameLikeAndRoleIsDel(String name, Long del);

    /**
     * 查询指定id的角色
     *
     * @param del
     * @return
     */
    public RoleEntity findRoleEntityByRoleIdAndAndRoleIsDel(Long id, Long del);

    /**
     * 根据角色ID分类查询所有功能，并将该角色拥有的功能标'1'，没有的标'0'
     *
     * @param roleId
     * @param ftId
     * @return
     */
    @Query(nativeQuery = true, value = "select FC_ID,FC_NAME," +
            "(case when FC_ID in (select FC_ID from USER_CRM.ROLE_FC" +
            " where ROLE_ID=?1 and role_fc_is_del=0) then 1 else 0 end) selected " +
            "from USER_CRM.TB_FUNCTIONS fc where FC_TYPE_ID=?2")
    public List<Object[]> queryFunctionsByRoleId(Long roleId, Long ftId);

    /**
     * 根据角色ID分部门查询所有用户，并将该角色拥有的用户标'1'，没有的标'0'
     *
     * @param roleId
     * @param deptId
     * @return
     */
    @Query(nativeQuery = true, value = "select user_id, user_NAME, " +
            "(case when user_ID in (select user_ID from TB_USER_ROLE " +
            "where ROLE_ID=?1 and user_role_is_del=0) then 1 else 0 end)" +
            " selected from TB_USER where DEPT_ID=?2 and USER_IS_DIMISSION=0")
    public List<Object[]> queryUsersByRoleId(Long roleId, Long deptId);

//    @Query(nativeQuery = true, value = "select FC_ID")
//    public List<Long> queryFcsByRoleId(Long roleId);

    /**
     * 根据角色名称模糊查询
     * @param name
     * @param del
     * @return
     */
    public List<RoleEntity> findAllByRoleNameLikeAndRoleIsDel(String name, Long del, Pageable pageable);
}
